import clsx from 'clsx';
import AiCard from './AICard';
import { Fragment, useContext, useEffect, useRef, useState } from 'react';
import { useDify } from '@/hooks/useDify';
import { Button, Skeleton } from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import { DocxContext } from '@/contexts/DocxContext';

interface Props {
  classnames?: string;
  retryCount: number;
  requestBody: any[];
  rendering: boolean;
  isDownload: boolean;
  handleDownload: () => void;
  onError: (error: Error) => void;
  onFinished: () => void;
}

export default function ResponseCard({
  handleDownload,
  onError,
  onFinished,
  classnames: className,
  requestBody,
  retryCount,
  rendering,
  isDownload,
}: Props) {
  const { nodes, processStream } = useDify();
  const [currentStep, setCurrentStep] = useState(0);
  const [stepResults, setStepResults] = useState<any[]>([]); // 存储每步的结果数据
  const [allStepsCompleted, setAllStepsCompleted] = useState(false);
  const [cards, setCards] = useState<any[]>([]);
  const [isFinished, setIsFinished] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const { docxRef } = useContext(DocxContext);

  useEffect(() => {
    setCards((prev) => {
      const result = [];
      let nodeIndex = 0;

      for (let i = 0; i < prev.length; i++) {
        const card = prev[i];
        if (card.fromNodes) {
          // 用新的 node 替换旧的 fromNodes 卡片
          if (nodeIndex < nodes.length) {
            result.push({ ...nodes[nodeIndex], fromNodes: true });
            nodeIndex++;
          }
          // 否则跳过（说明 nodes 数量减少了）
        } else {
          result.push(card);
        }
      }

      // 如果 nodes 数量增加，补上新卡片
      for (; nodeIndex < nodes.length; nodeIndex++) {
        result.push({ ...nodes[nodeIndex], fromNodes: true });
      }

      return result;
    });
  }, [nodes]);

  // 执行指定步骤
  const executeStep = async (stepIndex: number) => {
    if (stepIndex >= requestBody.length) return;

    try {
      const currentRequest = requestBody[stepIndex];

      // 如果当前步骤是组件渲染
      if (currentRequest.component) {
        // 检查是否有依赖
        if (currentRequest.dependsOn) {
          // 收集依赖的结果
          const dependencies: Record<string, any> = {};

          if (Array.isArray(currentRequest.dependsOn)) {
            // 如果 dependsOn 是数组，按索引获取结果
            currentRequest.dependsOn.forEach((depIndex: number) => {
              if (stepResults[depIndex]) {
                dependencies[`step_${depIndex}`] = stepResults[depIndex];
              }
            });
          } else if (typeof currentRequest.dependsOn === 'object') {
            // 如果 dependsOn 是对象映射，按 ID 获取结果
            Object.entries(currentRequest.dependsOn).forEach(
              ([key, stepIndex]) => {
                if (stepResults[stepIndex as number]) {
                  dependencies[key] = stepResults[stepIndex as number];
                }
              }
            );
          }

          // 预先设置为依赖数据
          setStepResults((prev) => {
            const newResults = [...prev];
            newResults[stepIndex] = dependencies;
            return newResults;
          });

          const componentResult = currentRequest.component(
            dependencies,
            (values: any) => {
              setStepResults((prev) => {
                const newResults = [...prev];
                newResults[stepIndex] = values;
                return newResults;
              });
            }
          );

          setCards(() => [...cards, componentResult]);
        } else {
          // 没有依赖，直接渲染组件
          const componentResult = currentRequest.component(
            {},
            (values: any) => {
              setStepResults((prev) => {
                const newResults = [...prev];
                newResults[stepIndex] = values;
                return newResults;
              });
            }
          );

          setCards(() => [...cards, componentResult]);
        }

        return;
      }

      // 原有的 requester 处理逻辑
      let requester;

      // 检查是否有依赖和依赖处理函数
      if (
        currentRequest.dependsOn &&
        typeof currentRequest.requester === 'function'
      ) {
        setIsFinished(false);

        // 收集依赖的结果
        const dependencies: Record<string, any> = {};

        if (Array.isArray(currentRequest.dependsOn)) {
          // 如果 dependsOn 是数组，按索引获取结果
          currentRequest.dependsOn.forEach((depIndex: number) => {
            if (stepResults[depIndex]) {
              dependencies[`step_${depIndex}`] = stepResults[depIndex];
            }
          });
        } else if (typeof currentRequest.dependsOn === 'object') {
          // 如果 dependsOn 是对象映射，按 ID 获取结果
          Object.entries(currentRequest.dependsOn).forEach(
            ([key, stepIndex]) => {
              if (stepResults[stepIndex as number]) {
                dependencies[key] = stepResults[stepIndex as number];
              }
            }
          );
        }

        // 传入依赖结果创建请求
        requester = currentRequest.requester(dependencies);
      } else {
        // 没有依赖，直接使用请求
        requester =
          typeof currentRequest.requester === 'function'
            ? currentRequest.requester()
            : currentRequest.requester;
      }

      // 执行请求
      const output = (await processStream(requester)) as string;
      if (output) {
        try {
          const parsedData = JSON.parse(output);
          setIsFinished(true);

          docxRef.current = {
            ...docxRef.current,
            ...parsedData,
          };

          // 保存当前步骤结果
          setStepResults((prev) => {
            const newResults = [...prev];
            newResults[stepIndex] = parsedData;
            return newResults;
          });

          // 检查是否是最后一步
          if (stepIndex === requestBody.length - 1) {
            setAllStepsCompleted(true);
            onFinished();
          }
        } catch (error) {
          console.error(error);
        }
      }
    } catch (error) {
      console.error(error);
      onError(error as Error);
    }
  };

  // 处理下一步
  const handleNextStep = async () => {
    const nextStep = currentStep + 1;
    if (nextStep < requestBody.length) {
      console.log(nextStep);
      setCurrentStep(nextStep);
      // 直接使用计算出的下一步索引执行
      await executeStep(nextStep);
    }
  };

  // 初始化或重试时执行第一步
  useEffect(() => {
    setCurrentStep(0);
    setStepResults([]);
    setAllStepsCompleted(false);
    executeStep(0);
  }, [retryCount]);

  return (
    <div className={clsx('flex flex-col gap-4', className)}>
      {/* 步骤进度指示器 */}
      <div className="mb-4 flex items-center gap-2">
        <span className="text-semi-color-text-2">
          步骤 {currentStep + 1} / {requestBody.length}
        </span>
        <div className="h-2 flex-1 rounded-full bg-gray-200">
          <div
            className="h-2 rounded-full bg-blue-500 transition-all duration-300"
            style={{
              width: `${((currentStep + (isFinished ? 1 : 0)) / requestBody.length) * 100}%`,
            }}
          ></div>
        </div>
      </div>

      <Skeleton
        placeholder={
          <div>
            <div className="mb-4 flex items-center gap-2 text-semi-color-text-2">
              <Icon icon={'mingcute:ai-line'}></Icon>
              <p>等待智能体响应...</p>
            </div>
            <Skeleton.Paragraph rows={5} className="mb-4 w-[100%]" />
          </div>
        }
        loading={isLoading}
        active
      >
        {cards.map((card) => {
          if (card.fromNodes) {
            return (
              <Fragment key={card.id}>
                <AiCard
                  key={card.id}
                  title={card.title}
                  description={card.message}
                  isStreaming={card.isStreaming}
                ></AiCard>
              </Fragment>
            );
          } else {
            return <>{card}</>;
          }
        })}

        {/* 当前步骤进行中 */}
        {!isFinished && (
          <div className="mx-auto mb-4 flex animate-pulse items-center gap-2 text-semi-color-text-2">
            <Icon icon={'mingcute:ai-line'}></Icon>
            <p>
              正在生成设计方案... (步骤 {currentStep + 1}/{requestBody.length})
            </p>
          </div>
        )}

        {/* 步骤控制按钮 */}
        {isFinished && !allStepsCompleted && (
          <div className="my-4 flex justify-center space-x-4">
            <Button type="primary" onClick={handleNextStep} className="w-32">
              下一步 ({currentStep + 2}/{requestBody.length})
            </Button>
          </div>
        )}

        {/* 当前步骤进行中 */}
        {rendering && (
          <div className="mx-auto mb-4 flex animate-pulse items-center gap-2 text-semi-color-text-2">
            <Icon icon={'bi:filetype-docx'}></Icon>
            <p>
              正在渲染文档...
            </p>
          </div>
        )}

        {/* 所有步骤完成后的下载按钮 */}
        {allStepsCompleted && !rendering && (
          <div className="flex space-x-4">
            <Button
              type="primary"
              className="my-[16px] w-32"
              onClick={handleDownload}
              loading={isDownload}
            >
              下载设计方案
            </Button>
          </div>
        )}
      </Skeleton>
    </div>
  );
}
